//
//  CZOauthViewController.swift
//  weibo
//
//  Created by Mac on 16/5/14.
//  Copyright © 2016年 fengzhixiang. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOauthViewController: UIViewController {

    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = GlobalBKGColor

        //设置导航栏
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        //标题
        navigationItem.title = "登录"

        //使用webview加载登录界面
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        SVProgressHUD.showWithStatus("缓慢加载中")

    }
    // MARK: - 点击事件
    @objc private func autoFill (){
//        CZPrint(items: "还有谁...比我帅!")
        let jsString = "document.getElementById('userId').value='513234428@qq.com';document.getElementById('passwd').value='feng36305050';"
        //使用webview执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    @objc private func close (){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }


    // MARK: - 懒加载
    /**
    *  webView
    */
    private lazy var webView: UIWebView = UIWebView()

}

extension CZOauthViewController: UIWebViewDelegate{
    /**
    *  webView加载完成调用
    */
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    // webView加载网页的时候回调用这个方法,加载一次回调一次,询问我们是否要加载某个请求
    // return true可以加载这个界面
    // teturn false就不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        // 点击授权: http://www.baidu.com/?code=46f61a46f57a8929fa4bb0c1a27a6e84
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        let url = request.URL!
        //截取返回链接字符串的头部,判断是否跟授权回调地址相同,如果不是就让他去加载
        if url.absoluteString.hasPrefix(redirect_uri){
            //如果是回调地址,不能让他加载,我们自己来做一些操作
            //拿到url中?号后面的字符串
            let query = url.query!
            let codeString = "code="
            // 如果query 是以 code=开头表示点击的授权按钮
            if query.hasPrefix(codeString){
                // 从query中截取code的值,substringFromIndex从指定位置截取到最后
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                //拿到code,在CZUserAccountViewModel
                ///加载AccessToken,字典转模型,模型保存到沙盒
                CZUserAccountViewModel.shareInstanse.loadAccountToken(code, callback: { (error) -> () in
                    //出现了错误
                    SVProgressHUD.showErrorWithStatus("网络不给力!!")

                    //延迟一秒关闭
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(Int64)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        self.close()
                    })

                })

            } else {
                close()//点击了取消按钮
            }

        } else { return true }

        return false
    }









}





